package yz.cp.back.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import yz.cp.back.admin.service.MessageManage;
import yz.cp.back.common.base.BaseController;
import yz.cp.back.common.constant.CommonConstant;
import yz.cp.back.common.res.ApiResult;
import yz.cp.back.common.vo.SearchVo;
import yz.cp.back.s.entity.SysMessage;
import yz.cp.back.s.entity.SysMessageSend;
import yz.cp.back.s.entity.SysUser;
import yz.cp.back.s.service.ISysMessageSendService;
import yz.cp.back.s.service.ISysMessageService;
import yz.cp.back.s.service.ISysUserService;

import java.util.ArrayList;
import java.util.List;


/**
 * @author Exrick
 */
@Slf4j
@RestController
@RequestMapping("/web/message")
@Transactional
public class MessageController extends BaseController {

    @Autowired
    private ISysMessageService messageService;

    @Autowired
    private ISysMessageSendService sendService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Autowired
    private MessageManage messageManage;
    @RequestMapping(value = "/getByCondition",method = RequestMethod.GET)
    public ApiResult getByCondition(@ModelAttribute SysMessage message,
                                    @ModelAttribute SearchVo searchVo){

        IPage<SysMessage> page = messageManage.findByCondition(message, searchVo);
        return renderOk().add(page);
    }

    @RequestMapping(value = "/get/{id}",method = RequestMethod.GET)
    public ApiResult get(@PathVariable String id){
        SysMessage message = messageService.getById(id);
        return renderOk().add(message);
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public ApiResult addMessage(@ModelAttribute SysMessage message){

        messageService.save(message);
        // 保存消息发送表
        List<SysMessageSend> messageSends = new ArrayList<>();
        if(CommonConstant.MESSAGE_RANGE_ALL.equals(message.getRange())){
            // 全体
            List<SysUser> allUser = userService.list();
            allUser.forEach(u->{
                SysMessageSend ms = new SysMessageSend();
                ms.setMessageId(message.getId());
                ms.setUserId(u.getId());
                messageSends.add(ms);
            });
            // 推送
            messagingTemplate.convertAndSend("/topic/handle", "您收到了新的系统消息");
        }else{
            // 指定用户
            for(String id:message.getUserIds()){
                SysMessageSend ms = new SysMessageSend();
                ms.setMessageId(message.getId());
                ms.setUserId(id);
                messageSends.add(ms);
                // 指定用户
                messagingTemplate.convertAndSendToUser(id,"/queue/subscribe", "您收到了新的消息");
            }
        }
        sendService.saveOrUpdateBatch(messageSends);
        return renderOk("添加成功");
    }

    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    public ApiResult editMessage(@ModelAttribute SysMessage message){
         messageService.updateById(message);
        return  renderOk("编辑成功");
    }

    @RequestMapping(value = "/delByIds/{ids}",method = RequestMethod.DELETE)
    public ApiResult delMessage(@PathVariable String[] ids){

        for(String id:ids){
            messageService.removeById(id);
            // 删除发送表
            sendService.remove(new QueryWrapper<SysMessageSend>().lambda().eq(SysMessageSend::getMessageId,id));
        }
        return renderOk("编辑成功");
    }
}
